package com.cly.config;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cly.base.contants.UserConstants;
import com.cly.utils.BaseContext;
import com.cly.utils.RedisClientsUtils;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * MyBatisPlus全局配置
 *
 * @author : 小雷
 * <p>
 * 2023-11-14 00:21:29
 */
@Component
@RequiredArgsConstructor
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * Redis 客户端
     */
    private final RedisClientsUtils redisClientsUtils;


    /**
     * 数据添加是: 自动填充策略
     *
     * @param metaObject 参数对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long id = redisClientsUtils.getGlobalData(UserConstants.ID, Long.class);
        if (Objects.isNull(id)) {
            id = 0L;
        }
        initData(metaObject, FieldFill.INSERT_UPDATE);
        // 自动填充创建时间和创建人
        this.strictInsertFill(metaObject, "createTime", String.class, BaseContext.date());
        this.strictInsertFill(metaObject, "createUser", Long.class, id);
        // 自动填充更新时间和更新人
        this.strictUpdateFill(metaObject, "updateTime", String.class, BaseContext.date());
        this.strictUpdateFill(metaObject, "updateUser", Long.class, id);
    }

    /**
     * 数据修改时填充策略
     *
     * @param metaObject 参数对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long id = redisClientsUtils.getGlobalData(UserConstants.ID, Long.class);
        if (Objects.isNull(id)) {
            id = 0L;
        }
        initData(metaObject, FieldFill.UPDATE);
        // 自动填充更新时间和更新人
        this.strictUpdateFill(metaObject, "updateTime", String.class, BaseContext.date());
        this.strictUpdateFill(metaObject, "updateUser", Long.class, id);
    }

    /**
     * 填充空值防止自动填充失败
     *
     * @param metaObject 参数对象
     * @param fill       填充策略
     */
    private void initData(MetaObject metaObject, FieldFill fill) {
        if (fill == FieldFill.INSERT || fill == FieldFill.INSERT_UPDATE) {
            metaObject.setValue("createTime", null);
            metaObject.setValue("createUser", null);
        }
        if (fill == FieldFill.UPDATE || fill == FieldFill.INSERT_UPDATE) {
            metaObject.setValue("updateTime", null);
            metaObject.setValue("updateUser", null);
        }
    }
}